# Copyright 2022 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Cleanup registries
on:
  schedule:
  - cron:  '12 0 * * *'
  workflow_dispatch:

env:
  WERF_DRY_RUN: "false"
{!{ tmpl.Exec "werf_envs" | strings.Indent 2 }!}

# Always run a single job at a time.
# Note: Concurrency is currently in beta and subject to change.
# https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#concurrency
concurrency:
  group: schedule-cleanup

jobs:
# Note: git_info is needed for werf.yaml
{!{ tmpl.Exec "git_info_job" . | strings.Indent 2 }!}

  cleanup_registry:
    name: Cleanup registry
    needs:
      - git_info
    runs-on: [self-hosted, regular]
    steps:
{!{ tmpl.Exec "checkout_full_step" . | strings.Indent 6 }!}
{!{ tmpl.Exec "login_dev_registry_step" . | strings.Indent 6 }!}
{!{ tmpl.Exec "werf_install_step" . | strings.Indent 6 }!}
      - name: Cleanup
        env:
          CI_COMMIT_TAG: ${{needs.git_info.outputs.ci_commit_tag}}
          CI_COMMIT_REF_NAME: ${{needs.git_info.outputs.ci_commit_ref_name}}
          ENABLE_REGISTRY_CLEANUP: ${{secrets.ENABLE_REGISTRY_CLEANUP}}
        run: |
          if [[ ${ENABLE_REGISTRY_CLEANUP} != "true" ]] ; then
            echo "⚓️ [$(date -u)] ENABLE_REGISTRY_CLEANUP is not 'true', skip running 'werf cleanup'."
            exit 0
          fi

          export WERF_REPO=${DEV_REGISTRY_PATH}
          type werf && source $(werf ci-env github --config werf_cleanup.yaml --verbose --as-file)
          werf cleanup --config werf_cleanup.yaml --without-kube
